import threading
import tkinter as tk
from tkinter import ttk, simpledialog, StringVar  # 导入 simpledialog 用于创建输入对话框
from tkinter import OptionMenu  # 导入 OptionMenu 用于下拉选择

import win32gui
from pynput import mouse

from pk.Baicaogu import Baicaogu
from pk.MoveWin import MoveWin
from pk.Watu import Watu
from pk.WindowManager import WindowManager
from pk.Yabiao import Yabiao
from pk.Zhuagui import Zhuagui


class SetupUi:
    def __init__(self):
        self.btn_baicaogu = None
        self.btn_yabiao = None
        self.btn_watu = None
        self.btn_zg = None
        self.status_label = None
        self.btn_toggle = None
        self.root = tk.Tk()
        self.root.title("Mh助手-V1.0")
        self.root.geometry("750x400")

        # 获取窗口自身位置信息
        self.window_rect = WindowManager.get_window_rect()
        # 创建主容器
        self.main_frame = tk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        self.main_frame.grid_columnconfigure(0, weight=1)  # 左列权重为1
        self.main_frame.grid_columnconfigure(1, weight=1)  # 右列权重为1
        # 初始化列表组件
        self.create_list_widget()
        # 添加操作按钮
        self.create_buttons_widget()

        # 状态管理
        self.capturing = False
        self.listener = None
        self.selectHwnd = []
        self.handles = set()
        self.watu_threads = []  # 用于存储所有挖图线程
        self.stop_watu = threading.Event()
        self.zg_threads = []  # 用于存储所有抓鬼线程
        self.stop_zg = threading.Event()
        # 添加日志组件
        self.log_text = tk.Text(self.root, height=5, state=tk.DISABLED)
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 新增：初始化句柄和种族的映射
        self.handle_race_map = {}
        # 定义种族选项
        self.races = ["人族", "仙族", "魔族"]

    def create_buttons_widget(self):
        btn_frame = ttk.LabelFrame(self.main_frame, text="按钮面板")
        btn_frame.grid(row=0, column=1, padx=10, pady=5, sticky="nsew")

        # 配置列权重使按钮能横向扩展
        btn_frame.grid_columnconfigure(0, weight=1)

        movewin = MoveWin(self)
        # 添加按钮（使用grid垂直排列）
        btn_adjustment = tk.Button(btn_frame, text="调整界面", command=movewin.btn_command)
        btn_adjustment.grid(row=0, column=0, padx=5, pady=2, sticky="ew")  # 调整界面

        watu_handler = Watu(self)
        self.btn_watu = tk.Button(btn_frame, text="自动挖图", command=watu_handler.btn_command)
        self.btn_watu.grid(row=1, column=0, padx=5, pady=2, sticky="ew")

        zhuagui_handler = Zhuagui(self)
        self.btn_zg = tk.Button(btn_frame, text="自动抓鬼", command=zhuagui_handler.btn_command)
        self.btn_zg.grid(row=2, column=0, padx=5, pady=2, sticky="ew")

        yabiao_handler = Yabiao(self)
        self.btn_yabiao = tk.Button(btn_frame, text="自动押镖", command=yabiao_handler.btn_command)
        self.btn_yabiao.grid(row=3, column=0, padx=5, pady=2, sticky="ew")

        baicaogu_handler = Baicaogu(self)
        self.btn_baicaogu = tk.Button(btn_frame, text="自动百草谷打怪", command=baicaogu_handler.btn_command)
        self.btn_baicaogu.grid(row=4, column=0, padx=5, pady=2, sticky="ew")

        tk.Button(btn_frame, text="其他功能开发中，敬请期待").grid(row=5, column=0, padx=5, pady=2, sticky="ew")

    def create_list_widget(self):
        # 创建带滚动条的Treeview
        # 控制面板
        control_frame = ttk.LabelFrame(self.main_frame, text="列表面板")
        control_frame.grid(row=0, column=0, padx=10, pady=5, sticky="nsew")

        tree_frame = tk.Frame(control_frame)
        tree_frame.pack(fill=tk.BOTH, expand=True)
        tree_frame.config(width=320)  # 覆盖为固定像素宽度
        # 垂直滚动条
        self.v_scroll = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL)

        # 配置列表列
        self.tree = ttk.Treeview(
            tree_frame,
            columns=("hwnd", "title", "dropdown", "remark"),  # 增加 dropdown 列
            yscrollcommand=self.v_scroll.set,
            selectmode="extended"  # 可改为 extended 支持多选
        )

        # 配置滚动条
        self.v_scroll.config(command=self.tree.yview)

        # 布局组件
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.v_scroll.pack(side=tk.RIGHT, fill=tk.Y)

        # 配置列参数
        self.tree.column("#0", width=0, stretch=tk.NO)  # 隐藏首列
        self.tree.heading("hwnd", text="句柄", anchor=tk.W)
        self.tree.heading("title", text="标题", anchor=tk.CENTER)
        self.tree.heading("dropdown", text="种族", anchor=tk.CENTER)  # 新列标题
        self.tree.heading("remark", text="备注", anchor=tk.CENTER)

        # 设置列宽
        self.tree.column("hwnd", width=80, minwidth=100, stretch=False)
        self.tree.column("title", width=100, anchor=tk.CENTER, stretch=False)
        self.tree.column("dropdown", width=120, anchor=tk.CENTER, stretch=False)  # 新列宽度
        self.tree.column("remark", width=180, anchor=tk.CENTER, stretch=False)

        # 按钮容器
        btn_frame = tk.Frame(control_frame)
        btn_frame.pack(fill=tk.X, pady=5)

        # 添加按钮
        self.btn_toggle = tk.Button(btn_frame, text="开始捕获", command=self.toggle_capture)
        self.btn_toggle.pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="删除选中", command=self.delete_selected).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="清空列表", command=self.clear_list).pack(side=tk.LEFT, padx=5)
        self.status_label = ttk.Label(btn_frame, text="捕获状态：停止中")
        self.status_label.pack(side=tk.RIGHT, padx=5)
        self.tree.bind("<<TreeviewSelect>>", self.on_select)
        # 绑定鼠标双击事件到下拉选择列和备注列
        self.tree.bind("<Double-1>", self.on_double_click)

    def on_select(self, event):
        selected = self.tree.selection()
        self.selectHwnd = []
        self.handle_race_map = {}
        for item_id in selected:
            self.selectHwnd.append(self.tree.item(item_id, "values")[0])
            self.handle_race_map[self.tree.item(item_id, "values")[0]] = self.tree.item(item_id, "values")[2]

    def is_in_self_window(self, x, y):
        """判断坐标是否在程序窗口范围内"""
        left, top, right, bottom = self.window_rect
        return left <= x <= right and top <= y <= bottom

    def on_click(self, x, y, button, pressed):
        """右键点击事件处理（带区域过滤）"""
        if button == mouse.Button.right and pressed and self.capturing:
            if self.is_in_self_window(x, y):
                return  # 忽略自身窗口区域

            hwnd = win32gui.WindowFromPoint((x, y))
            if hwnd not in self.handles:
                info = WindowManager.get_window_info(hwnd)
                if info:
                    # 示例添加新记录，初始化 dropdown 列值为空
                    # info = (*info[:2], "",*info[3:])
                    self.tree.insert("", tk.END, values=info)
                    self.tree.see(self.tree.get_children()[-1])  # 滚动到新项
                    self.add_log(f"添加窗口：{info[1]}")
                    # 新增：更新句柄和种族的映射
                    self.handle_race_map[info[0]] = info[2]

    def delete_selected(self):
        selected_items = self.tree.selection()
        for item in selected_items:
            values = self.tree.item(item, "values")
            hwnd = values[0]
            self.tree.delete(item)
            # 新增：删除映射中的记录
            if hwnd in self.handle_race_map:
                del self.handle_race_map[hwnd]
        self.add_log("删除选中窗口")

    def clear_list(self):
        for item in self.tree.get_children():
            values = self.tree.item(item, "values")
            hwnd = values[0]
            self.tree.delete(item)
            # 新增：删除映射中的记录
            if hwnd in self.handle_race_map:
                del self.handle_race_map[hwnd]
        self.add_log("清空列表")

    def toggle_capture(self):
        """切换捕获状态（即时响应）"""
        self.capturing = not self.capturing
        self.window_rect = WindowManager.get_window_rect()  # 刷新窗口位置

        if self.capturing:
            self.btn_toggle.config(text="停止捕获")
            self.status_label.config(text="捕获状态：捕获中")
            self.start_listener()
            self.add_log("开始捕获窗口")
        else:
            self.btn_toggle.config(text="开始捕获")
            self.status_label.config(text="捕获状态：已停止")
            self.stop_listener()
            self.add_log("停止捕获窗口")

    def start_listener(self):
        """启动监听线程"""
        self.listener = mouse.Listener(on_click=self.on_click)
        self.listener_thread = threading.Thread(target=self.listener.start)
        self.listener_thread.daemon = True
        self.listener_thread.start()

    def stop_listener(self):
        """安全停止监听"""
        if self.listener:
            self.listener.stop()
            self.listener = None

    def add_log(self, message):
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, f"{message}\n")
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)

    def on_double_click(self, event):
        # 获取点击的行和列
        region = self.tree.identify("region", event.x, event.y)
        if region == "cell":
            col = self.tree.identify_column(event.x)
            item = self.tree.identify_row(event.y)
            self.add_log(f"更新窗口 {col} ")
            if col == "#3":  # 检查是否点击了下拉选择列
                current_value = self.tree.item(item, "values")[2]
                # 创建一个临时窗口用于显示下拉框
                top = tk.Toplevel(self.root)
                top.title("选择种族")
                var = StringVar(top)
                var.set(current_value if current_value in self.races else self.races[0])
                # 设置字体大小和宽度来调大下拉框
                option_menu = OptionMenu(top, var, *self.races)
                option_menu.config(width=10)  # 设置字体和宽度
                option_menu.pack(padx=70, pady=40)

                def save_selection():
                    new_race = var.get()
                    values = self.tree.item(item, "values")
                    new_values = (values[0], values[1], new_race, values[3])
                    self.tree.item(item, values=new_values)
                    self.add_log(f"更新窗口 {values[1]} 的种族为: {new_race}")
                    # 新增：更新句柄和种族的映射
                    self.handle_race_map[values[0]] = new_race
                    top.destroy()

                save_button = tk.Button(top, text="保存", command=save_selection)
                save_button.pack(pady=10)

            elif col == "#4":  # 检查是否点击了备注列
                current_remark = self.tree.item(item, "values")[3]
                new_remark = simpledialog.askstring("编辑备注", "请输入新的备注",  parent=self.root, initialvalue=current_remark)
                if new_remark is not None:
                    values = self.tree.item(item, "values")
                    new_values = (values[0], values[1], values[2], new_remark)
                    self.tree.item(item, values=new_values)
                    self.add_log(f"更新窗口 {values[1]} 的备注为: {new_remark}")
